import json
from datetime import datetime
from models import init_db, Session, Calculator, Task, UserAuditLog, CalculatorAuditLog, DraftInput

def migrate_data():
    """迁移现有JSON数据到SQLite数据库"""
    init_db()
    session = Session()

    try:
        # 迁移计算器数据
        with open('calculators.json', 'r', encoding='utf-8') as f:
            calculators = json.load(f)
            for i, calc in enumerate(calculators, 1):
                calculator = Calculator(
                    name=calc['name'],
                    version=1,
                    code=calc['code'],
                    status=calc['status'],
                    inputs=calc['inputs'],
                    access_control=calc.get('access_control', {"type": "all", "allowed_users": []})
                )
                session.add(calculator)

        # 迁移任务数据
        with open('tasks.json', 'r', encoding='utf-8') as f:
            tasks = json.load(f)
            for task in tasks:
                new_task = Task(
                    calculator_id=task['calculator_id'],
                    username=task['username'],
                    inputs=task['inputs'],
                    output=task['output'],
                    timestamp=datetime.strptime(task['timestamp'], "%Y-%m-%d %H:%M:%S"),
                    calculator_version=1
                )
                session.add(new_task)

        # 迁移草稿输入数据
        try:
            with open('draft_inputs.json', 'r', encoding='utf-8') as f:
                drafts = json.load(f)
                for draft in drafts:
                    new_draft = DraftInput(
                        id=draft['id'],
                        calculator_id=draft['calculator_id'],
                        username=draft['username'],
                        data=draft['data'],
                        timestamp=datetime.fromisoformat(draft['timestamp'])
                    )
                    session.add(new_draft)
        except FileNotFoundError:
            pass

        # 迁移用户审计日志
        try:
            with open('user_audit_logs.json', 'r', encoding='utf-8') as f:
                logs = json.load(f)
                for log in logs:
                    new_log = UserAuditLog(
                        timestamp=datetime.fromisoformat(log['timestamp']),
                        username=log['username'],
                        action=log['action'],
                        details=log['details']
                    )
                    session.add(new_log)
        except FileNotFoundError:
            pass

        # 迁移计算器审计日志
        try:
            with open('calculator_audit_logs.json', 'r', encoding='utf-8') as f:
                logs = json.load(f)
                for log in logs:
                    new_log = CalculatorAuditLog(
                        calculator_id=log['calc_id'],
                        timestamp=datetime.fromisoformat(log['timestamp']),
                        username=log['username'],
                        action=log['action'],
                        details=log['details'],
                        old_value=log.get('old_value'),
                        new_value=log.get('new_value')
                    )
                    session.add(new_log)
        except FileNotFoundError:
            pass

        session.commit()
        print("数据迁移完成")

    except Exception as e:
        session.rollback()
        print(f"迁移失败: {e}")
        raise
    finally:
        session.close()

if __name__ == "__main__":
    print("开始迁移数据...")
    init_db()  # 先初始化数据库表结构
    migrate_data()  # 再迁移数据
    print("迁移完成！")
